<style lang="less" scoped>
.yzm {
  position: absolute;
  top: 177px;
  left: -30px;
  z-index: 1001;
  width: 360px;
  box-shadow: 0px 0px 20px 0px #868686;
}
.yzmbox {
  a {
    width: 240px;
    height: 80px;
    margin: 0 auto;
  }
}
</style>

<template>
  <Modal v-draggable="options"
         v-model="modal"
         title="欢迎注册"
         width="300"
         :mask-closable="false">
    <Form ref="loginForm"
          :model="form"
          :rules="rules"
          @keydown.enter.native="handleSubmit">
      <FormItem prop="userName">
        <Input @on-focus="yzmfocus"
               v-model="form.userName"
               placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16"
                type="ios-person"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem prop="password">
        <Input @on-focus="yzmfocus"
               type="password"
               v-model="form.password"
               placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14"
                type="md-lock"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem prop="mobile">
        <Input @on-focus="yzmfocus"
               v-model="form.mobile"
               placeholder="请输入手机号">
        <span slot="prepend">
          <Icon type="md-phone-portrait" />
        </span>
        </Input>
      </FormItem>
      <FormItem prop="sms_code">
        <Input @on-focus="yzmfocus"
               ref="yzmInput"
               v-model="form.sms_code"
               placeholder="请输入短信验证码">
        <span slot="prepend">
          <Icon type="ios-send" />
        </span>
        <Button slot="append"
                @click="fsyzm"
                :disabled="sendMsgDisabled">{{sendMsgDisabled?time+'秒后重新获取':'获取短信验证码'}}</Button>
        </Input>
      </FormItem>
      <Alert v-if="aerr2"
             style="margin-top: 10px;margin: 0 auto;"
             type="error"
             show-icon>{{errText2}}</Alert>
      <Card class="yzm"
            v-if="txyzm">
        <FormItem prop="captchacode"
                  class="v-ivu-append">
          <div style="text-align: center;">请输入图形验证码</div>
          <div class="yzmbox">
            <a style="display:  block;"
               @click="getyzm"><img :src="this.Img"></a>
          </div>
          <Input @on-focus="yzmfocus"
                 style="margin-top: 10px;margin-left: 44px;width: 240px;"
                 ref="yzmInput"
                 size="large"
                 type="text"
                 v-model="form.captchaCode"
                 placeholder="请输入验证码">
          <span slot="prepend">
            <Icon :size="14"
                  type="md-umbrella" />
          </span>
          <Button slot="append"
                  icon="md-refresh"
                  @click="renovateCode"></Button>
          </Input>
          <Alert v-if="aerr"
                 style="margin-top: 10px;margin-left: 44px;width: 240px;"
                 type="error"
                 show-icon>{{errText}}</Alert>
          <div style="text-align: center;margin-top: 20px;">
            <Button type="primary"
                    @click="send">发送短信验证码</Button>
            <Button type="default"
                    @click="gbtxyzm">关闭</Button>
          </div>
        </FormItem>
      </Card>
    </Form>
    <div slot="footer">
      <Button @click="handleSubmit"
              type="primary"
              long>注册</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  name: 'RegisterForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        const validateUserName = (rule, value, callback) => {
          console.log(value.length)
          let re = /^[a-zA-Z0-9]([-a-zA-Z0-9]{2,9})+$/
          if (value.search(re) || value.length < 3 || value.length > 10) {
            return callback(new Error('用户名只能由3至10位的字母和数字组成'))
          } else {
            callback()
          }
        }
        return [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { validator: validateUserName, trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        const validatePassword = (rule, value, callback) => {
          if (value.length < 3 || value.length > 20) {
            return callback(new Error('密码长度错误,由3-20个字符组成'))
          } else {
            callback()
          }
        }
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    },
    captchacodeRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    },
    mobileRules: {
      type: Array,
      default: () => {
        const validateMobile = (rule, value, callback) => {
          let myreg = /^[1][3,4,5,7,8][0-9]{9}$/
          if (!myreg.test(value)) {
            callback(new Error('请输入正确的手机号'))
          } else {
            callback()
          }
        }
        return [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      }
    },
    sms_codeRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '请输入短信验证码', trigger: 'blur' }
        ]
      }
    },
    modalRegister: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      aerr: false,
      errText: '',
      aerr2: false,
      errText2: '',
      options: {
        trigger: '.ivu-modal-header',
        body: '.ivu-modal',
        recover: true
      },
      txyzm: false,
      time: 60, // 发送验证码倒计时
      sendMsgDisabled: false,
      modal: false,
      Img: '',
      form: {
        userName: '',
        password: '',
        captchacode: '',
        sms_code: '',
        mobile: '',
        CapKey: {
          key: ''
        }
      }
    }
  },
  watch: {
    modalRegister (value) {
      if (value === true) {
        this.yzmfocus()
        this.$refs.loginForm.resetFields()
        this.form.CapKey.key = ''
      }
      this.modal = value
    },
    modal (value) {
      this.$emit('on-modal-valid', value)
    }
  },
  created () {
    this.modal = this.modalRegister
  },
  computed: {
    rules () {
      return {
        userName: this.userNameRules,
        password: this.passwordRules,
        captchaCode: this.captchaCodeRules,
        mobile: this.mobileRules,
        sms_code: this.sms_codeRules
      }
    }
  },
  mounted () {
    console.log()
  },
  methods: {
    handleSubmit () {
      let _this = this
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$api.register({ name: this.form.userName, password: this.form.password, phone: this.form.mobile, sms_code: this.form.sms_code }).then(response => {
            response.json().then(res => {
              if (res.code === 2) {
                if (res.msg === '短信验证码不正确') {
                  _this.form.sms_code = ''
                }
                _this.aerr2 = true
                _this.errText2 = res.msg
              } else if (res.code === 1) {
                _this.modal = false
                this.$emit('on-success-valid', res)
              }
            })
          })
        }
      })
    },
    fsyzm () {
      this.formvalidata(['mobile', 'password', 'userName'], (valid) => {
        if (valid) {
          this.getyzm()
          this.yzmfocus()
          this.txyzm = true
          this.form.captchaCode = ''
        }
      })
    },
    formvalidata (arr, callback) {
      let v = []
      console.log(arr)
      for (let i = 0, len = arr.length; i < len; i++) {
        this.$refs.loginForm.validateField(arr[i], (valid) => {
          if (valid) {
            v.push(valid)
          }
        })
      }
      let a = v.length === 0 ? 1 : 0
      callback(a)
    },
    gbtxyzm () {
      this.txyzm = false
    },
    send () {
      let me = this
      if (this.form.captchaCode !== '') {
        this.$api.smsCode({ mobile: this.form.mobile, cap_key: this.form.CapKey.key, captcha: this.form.captchaCode }).then(response => {
          response.json().then(res => {
            if (res.code === 2) {
              this.getyzm()
              this.errText = res.msg
              this.aerr = true
            } else if (res.code === 1) {
              this.txyzm = false
              me.sendMsgDisabled = true
              this.$refs.yzmInput.focus()
              let interval = window.setInterval(function () {
                if ((me.time--) <= 0) {
                  me.time = 60
                  me.sendMsgDisabled = false
                  window.clearInterval(interval)
                }
              }, 1000)
            }
            console.log(res)
          })
        })
      } else {
        this.errText = '请输入图片里的验证码'
        this.aerr = true
      }
    },
    yzmfocus () {
      this.aerr = false
      this.aerr2 = false
      this.errText = ''
      this.errText2 = ''
    },
    renovateCode () {
      this.getyzm()
      this.$refs.yzmInput.focus()
    },
    getyzm () {
      let _this = this
      if (this.form.CapKey.key === '') {
        this.$api.getCaptcha().then(function (response) {
          _this.form.CapKey.key = response.headers.get('Set-Cap-Key')
          response.blob().then(function (responseBlob) {
            if (_this.Img) window.URL.revokeObjectURL(_this.Img)
            _this.Img = window.URL.createObjectURL(responseBlob)
          })
        })
      } else {
        this.$api.getCaptcha(this.form.CapKey).then(function (response) {
          response.blob().then(function (responseBlob) {
            if (_this.Img) {
              window.URL.revokeObjectURL(_this.Img)
            }
            _this.Img = window.URL.createObjectURL(responseBlob)
          })
        })
      }
    }
  }
}
</script>
